//
//  YSProdReviewsDetailCtrl.m
//  Yueshi
//
//  Created by Northwan on 15/9/24.
//  Copyright © 2015年 悦食中国. All rights reserved.
//  评价

#import "YSProdReviewsDetailCtrl.h"
#import "YSClubDataTool.h"
#import "YSProdReviewItemFrame.h"
#import "YSProdReviewCell.h"

@interface YSProdReviewsDetailCtrl ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (assign, nonatomic) NSInteger prodId;
@property (strong, nonatomic) NSMutableArray *allFrames;
@property (strong, nonatomic) NSMutableArray *itemArray;
@end

@implementation YSProdReviewsDetailCtrl

-(instancetype)initWithProdId:(NSInteger)prodId{
    self = [super init];
    if(self){
        self.prodId = prodId;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"评价"];
    
    _itemArray = [NSMutableArray array];
    _allFrames = [NSMutableArray array];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor  = PUBLIC_BG;
    self.tableView.separatorStyle =  UITableViewCellSeparatorStyleNone;
    self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    
    [self requestData:0];
}

-(void)footerRefresh{
    NSInteger lastComtId = 0;
    if(_itemArray.count){
        lastComtId = ((YSProdComment *)[_itemArray lastObject]).id;
    }
    [self requestData:lastComtId];
}

-(void)requestData:(NSInteger)lastCommentId{
    [YSClubDataTool getProductComment:_prodId lastCommentId:lastCommentId success:^(YSProductDetailRes *result) {
        [UIUtil refreshComplete:_tableView];
        if(result.isSucc){
            [_itemArray addObjectsFromArray:result.prodComment];
            [self itemArrayWithFrames];
        }
    } failure:^(NSError *error) {
        [UIUtil refreshComplete:_tableView];
        ShowTips(kRequestFailure);
    }];
}

-(void)itemArrayWithFrames{
    [_allFrames removeAllObjects];
    for (YSProdComment *comment in _itemArray) {
        YSProdReviewItemFrame *frame = [YSProdReviewItemFrame new];
        frame.comment  = comment;
        [_allFrames addObject:frame];
    }
    [_tableView reloadData];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _allFrames.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YSProdReviewCell *cell = [YSProdReviewCell cellWithTableView:tableView];
    [cell setReviewItemFrame:_allFrames[indexPath.row]];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [_allFrames[indexPath.row] cellHeight];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
